package br.com.remedioCerto.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import br.com.remedioCerto.R;
import br.com.remedioCerto.model.Horario;

public class HorarioAdapter extends BaseAdapter {
	private List<Horario> listaHorario;
	private Context context;
	
	
	public HorarioAdapter(Context context,List<Horario> lista) {
		this.listaHorario = lista;
		this.context = context;
	}
		
	@Override
	public int getCount() {
		return this.listaHorario.size(); 
	}
	
	@Override
	public Horario getItem(int position) {
		return this.listaHorario.get(position);
	}
	
	@Override
	public long getItemId(int position) {
		return position;
	}
	
	public void remove(Horario horario){
		listaHorario.remove(horario);
		notifyDataSetChanged();
	}
	
	public void remove(int position){
		listaHorario.remove(position);
		notifyDataSetChanged();
	}
	
	public List<Horario> getSelecionados(){
		List<Horario> retorno = new ArrayList<Horario>();
		for (Horario h : listaHorario) {
			if(h.isAtivo()) 
				retorno.add(h);
		}
		return retorno;
	}
	
	public void setSelecionados(List<Horario> lista) {
		for (Horario h : lista) {
			h.setAtivo(true);
			listaHorario.set(h.getHora(),h);
		}
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.horario_item_adapter,parent,false);
			
		
		CheckBox checkBox = (CheckBox) view.findViewById(R.id.item_check);
		checkBox.setOnClickListener(onClickListener);
		checkBox.setId(position);
		checkBox.setChecked(listaHorario.get(position).isAtivo());	
		
		TextView horario =(TextView) view.findViewById(R.id.item_horario);
		horario.setText(getHorarioFormatado(position));
		
		return view;
	}
		
	private String getHorarioFormatado(int position){
		String hora = listaHorario.get(position).getHora().toString();
		if(hora.length()==1)hora = "0"+hora;
		
		String min = listaHorario.get(position).getMinuto().toString();
		if(min.length()==1)min = "0"+min;
		
		return hora+":"+min;
	}

	private OnClickListener onClickListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			int pos = view.getId();
			boolean status = ((CheckBox) view).isChecked();
			listaHorario.get(pos).setAtivo(status);
		}
	};

}
